// pages/order/addorder.js
import http from '../../utils/http.js'
import moment from '../../utils/moment.js'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: app.globalData.imgDomain,
    shippingDay:"",
    shippingHour:"",
    startDate:'',
    endDate:'',
    postscript:'',
    cardName:'',
    addressInfo:{},
    goods:[],
    totalAmount:0,
    couponAmount:0,
    times: [],
    choseTimeIndex:0,
    couponCount:0,
    couponId:'',
    canUseCouponTxt:'',
    shippingFee:0.00,
    payId:'105',
    inputCouponId:'',
    payItems:[
      { name: '余额支付', value: 103,icon:'ye.png'},
      { name:'微信支付',value:105 ,icon:'wxpay.png'},
      { name: '货到付款', value: 104,icon:'df.png'}
    ],
    userMoney:0.00,
    orderSn:'',
    isCommonCoupon:false,
    showPlusAttr:false,
    tempCouponId:'',
    tempCouponTxt:'',
    isGroup:false,
    goodsAttrId:'',
    group:{},
    parentId:0,
    canUseCoupon:true
  },
  viewCouponList(){
    let me=this;
    if (!me.data.canUseCoupon){
      wx.showToast({
        icon: 'none',
        title: '您购买的商品不能使用优惠券哦'
      })
      return;
    }
    if(me.data.payId == '103'){
      wx.showToast({
        icon: 'none',
        title: '余额支付不能使用优惠券'
      })
      return;
    }
    if (me.data.couponId && me.data.couponId.length > 0 && me.data.isCommonCoupon 
      && me.data.inputCouponId && me.data.inputCouponId.length>0) {
      wx.showToast({
        icon: 'none',
        title: '优惠券和优惠码不能同时使用'
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/coupon/coupon'
    })
  },
  getUserMoney() {
    let me = this;
    let userId = wx.getStorageSync("userId");
    if(!userId){
      return;
    }
    http.request({
      url: 'user/getUserMoney/' + userId,
      success: res => {
        me.setData({
          userMoney: res
        });
      }
    });
  },
  createOrder(){
    let me=this;
    let userId = wx.getStorageSync("userId");
    if(!userId){
      wx.showToast({
        title: '您可能未登录或登录失效，请重新登录',
        icon:'none'
      })
      return;
    }
    if (!me.data.addressInfo.tel || me.data.addressInfo.tel.length==0){
      wx.showToast({
        icon:'none',
        title: '请选择一个送货地址'
      })
      return;
    }

    let cakeGood = me.data.goods.find(good=>{
      return good.goodsId != 119 && good.goodsId != 118 && good.goodsId != 73 
    })

    if (cakeGood && me.data.addressInfo.city != 220) {
      wx.showToast({
        icon: 'none',
        title: '您购买的商品目前只支持南京配送哦'
      })
      return;
    }

    if (me.data.shippingHour == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择送货时间'
      })
      return;
    }

    let payAmount = me.data.totalAmount - me.data.couponAmount;
    if (me.data.payId == 103 && me.data.userMoney < payAmount){
      wx.showModal({
        title: '订单提示',
        content: '您的余额不足，立即充值',
        success:res=>{
          if(res.confirm){
            wx.navigateTo({
              url: '/pages/user/recharge'
            })
          }
        }
      })
      return;
    }

    let payItem = me.data.payItems.find((item)=>{
      return item.value == me.data.payId;
    })
    
    let orderInfo = {
      shippingDay: me.data.shippingDay,
      shippingHour: me.data.shippingHour,
      payId:me.data.payId,
      cardName: me.data.cardName,
      postscript: me.data.postscript,
      province: me.data.addressInfo.province,
      city: me.data.addressInfo.city,
      district: me.data.addressInfo.district,
      shippingFee: me.data.shippingFee,
      consignee: me.data.addressInfo.consignee,
      tel: me.data.addressInfo.tel,
      address: me.data.addressInfo.address,
      couponId: me.data.couponId,
      payName: payItem.name,
      fromAd:101,
      referer:'小程序',
      orderGoods:me.data.goods,
      userId: userId,
      orderSn: me.data.orderSn,
      orderStatus:1,
      plusGoodAttrId: me.data.plusGoodAttrId,
      plusGoodsId:me.data.plusGoodsId,
      integral:!me.data.isGroup ? 0 : 1,
      agencyId:me.data.group.personNum,
      parentId: me.data.parentId
    }
    wx.showLoading({
      title: '正在下单'
    })
    http.request({
      url:'order/save',
      data: orderInfo,
      success:res=>{
        me.setData({
          orderSn: res.orderSn
        });
        wx.hideLoading();
        if (me.data.payId == 103 || me.data.payId == 104){
          wx.showModal({
            title: '小浮提醒',
            content: '您已成功下单，稍后会有客服与您联系。请您保持电话畅通！',
            showCancel:false,
            confirmText:'我知道了',
            success:ret=>{
              if(ret.confirm){
                wx.navigateTo({
                  url: './order_detail?orderCode=' + res.orderSn
                })
              }
            }
          })
          return;
        }
        if (me.data.payId == 105){
          if (res.moneyPaid > 0){
            me.createPrepay(res.orderSn);
          }else{
            wx.navigateTo({
              url: './order_detail?orderCode=' + res.orderSn
            })
          }
        }
      }
    });
  },

  createPrepay(orderCode){
    let me = this;
    http.request({
      url: 'wxPay/wxPrePay',
      data:{
        tradeId: orderCode,
        body:'浮遇纪cake',
        wxKey: app.getSessionKey()
      },
      success: res=>{
        if (res.code == "200") {
          if (res.msg) {
            var msg = res.msg;
            wx.requestPayment({
              timeStamp: msg.timeStamp.toString(),
              nonceStr: msg.nonceStr,
              package: msg.package,
              signType: 'MD5',
              paySign: msg.sign,
              success:res=>{
                wx.navigateTo({
                  url: './order_detail?orderCode=' + orderCode
                })
              },
              fail:res=>{
                if (res.errMsg === 'requestPayment:fail cancel'){
                  wx.showToast({
                    icon:'none',
                    title: '用户取消支付'
                  })
                  me.deletePayCancelOrder(orderCode);
                }
              },
              complete:res=>{
                console.log(res);
              }
            })
          }
        }
      }
    })
  },

  deletePayCancelOrder(orderCode){
    let me=this;
    http.request({
      url: 'order/deletePayCancelOrder/' + orderCode,
      success:res=>{
        console.log(res);
      }
    });
  },

  payItemChange(e){
    let me=this;
    if (!me.data.isGroup && e.detail.value == '103'){
      wx.showModal({
        title: '温馨提示',
        content: '余额支付将无法使用优惠券，确定切换吗？',
        success:res=>{
          if(res.confirm){
            me.setData({
              payId: e.detail.value,
              couponId:'',
              inputCouponId:'',
              tempCouponId: '',
              tempCouponTxt: '',
              couponAmount:0
            });
          }
        }
      })
    }else{
      me.setData({
        payId: e.detail.value
      });
    }
  },

  bindDateChange(e){
    this.setData({
      shippingDay:e.detail.value,
      shippingHour:'',
      choseTimeIndex:''
    },()=>{
      this.createTimes();
    });
  },
  bindTimeChange(e){
    this.setData({
      shippingHour: this.data.times[e.detail.value].val,
      choseTimeIndex: e.detail.value
    });
  },
  bindCardMsg(e) {
    this.setData({
      cardName: e.detail.value
    });
  },
  bindRemark(e){
    this.setData({
      postscript: e.detail.value
    });
  },
  buildCanUseConpon(goods){
    let canUseCouponGood = goods.find(item=>{
      return item.goodsId == 96 || item.catId == 24;
    })
    if (canUseCouponGood){
      return false;
    }else{
      return true;
    }
  },
  getOrderInfo(){
    let me=this;
    let userId = wx.getStorageSync("userId");
    if(!me.data.isGroup){
      http.request({
        url: 'order/getOrderInfo/' + userId,
        method: 'get',
        success: res => {
          if (!res.cartInfo.goods || res.cartInfo.goods.length==0){
            wx.navigateBack({})
            return;
          }
          let addressInfo = res.defaultAddress;
          console.log(addressInfo);
          if (!res.defaultAddress){
            addressInfo = { consignee:'请选择一个收货地址'}
          }
      
          me.setData({
            addressInfo: addressInfo,
            goods: res.cartInfo.goods,
            shippingFee:res.cartInfo.shippingFee,
            totalAmount: res.cartInfo.totalPrice,
            couponCount: res.couponCount,
            canUseCouponTxt: res.couponCount > 0 ? res.couponCount+'张可用' : '暂无可用',
            showPlusAttr:false,
            canUseCoupon: me.buildCanUseConpon(res.cartInfo.goods),
          });
          me.createTimes();
          me.getShipFee(addressInfo.provinceName);
        }
      });
    }else{
      http.request({
        url: 'order/getGroupBuyOrderInfo/' + userId + '/' + me.data.goodsAttrId,
        success: res => {
          let addressInfo = res.defaultAddress;
          if (!res.defaultAddress) {
            addressInfo = { consignee: '请选择一个收货地址' }
          }
          let good = {
            recId:'',
            orderId:'',
            goodsId: res.groupBuy.goodsId,
            goodsAttrId: res.groupBuy.goodsAttrId,
            goodsName: res.groupBuy.goodsName,
            goodsSn: res.groupBuy.goodsSn,
            goodsNumber:1,
            marketPrice: res.groupBuy.goodsPrice,
            goodsPrice:res.groupBuy.groupPrice,
            goodsAttr: res.groupBuy.attrName,
            goodsThumb: res.groupBuy.goodsThumb
          }
          me.setData({
            addressInfo: addressInfo,
            totalAmount: res.groupBuy.groupPrice,
            group: res.groupBuy,
            goods:[good],
            showPlusAttr: false,
            payItems: [
              { name: '余额支付', value: 103, icon: 'ye.png' },
              { name: '微信支付', value: 105, icon: 'wxpay.png' }
            ],
          });
          me.createTimes();
        }
      });
    }
  },

  createTimes(){
    let me=this;
    let min = 10;
    let max = 20;
    if(!me.data.isGroup){
      let todayIsSend = true;
      let shipDayDate = moment();
      if(me.data.shippingDay){
        shipDayDate = moment(me.data.shippingDay);
      }
      let nowHour = moment().hour();
      let nowMinute = moment().minute();
      let minTodayIsSendHour = 19 - 5;
      if (shipDayDate.year() === moment().year()){
        if (shipDayDate.month() === moment().month()) {
          if (shipDayDate.date() === moment().date()) {
            todayIsSend = true;
            if (nowHour >= minTodayIsSendHour) {
              todayIsSend = false;
            }
            me.data.startDate = todayIsSend ? moment().format('YYYY-MM-DD') : moment().add(1, 'd').format('YYYY-MM-DD')
          } else if (shipDayDate.date() > moment().date()) {
            todayIsSend = false;
            me.data.startDate = me.data.shippingDay;
          }
        
          let startDateDate = moment(me.data.startDate);
          if (!todayIsSend) {
            if (nowHour >= 20) {
              let daylength = startDateDate.date() - moment().date();
              if (daylength > 1) {
                min = 10;
              } else if (daylength == 1) {
                min = 12;
              }
            }
          } else {
            if (nowHour < 8){
              min = 12;
            }else{
              let step = nowMinute >= 30 ? 6 : 5;
              min = nowHour + step;
              console.log(todayIsSend, min);
            }
          }
        } else if (shipDayDate.month() > moment().month()){
          me.data.startDate = me.data.shippingDay;
        }
      } else if (shipDayDate.year() > moment().year()){
        me.data.startDate = me.data.shippingDay;
      }
      
      //特别商品时间改变
      let teGood = me.buildCanUseConpon(me.data.goods);
      if(!teGood){
        let nowHour = moment().hour();
        if (shipDayDate.year() === moment().year()) {
          if (shipDayDate.month() === moment().month()) {
            if (shipDayDate.date() === moment().date() || shipDayDate.date() - moment().date() == 1) {
              if (nowHour>=20){
                me.data.startDate = moment().add(2, 'd').format('YYYY-MM-DD');
                min = 10;
              }else if(nowHour < 10){
                me.data.startDate = moment().add(1, 'd').format('YYYY-MM-DD')
                min = 10;
              } else if (nowHour >= 10 && nowHour < 20){
                me.data.startDate = moment().add(1, 'd').format('YYYY-MM-DD')
                min = nowHour;
              }
            }
          }
        }
      }

      me.data.times=[];
      me.data.endDate = moment().add(1, 'y').format('YYYY-MM-DD')
      for(let i=min;i < max;i++){
        me.data.times.push({
          val:i,
          display:i+':00-'+(i+1)+':00'
        });
      }
      me.setData({
        shippingDay: me.data.startDate,
        startDate: moment().format('YYYY-MM-DD'),
        endDate: me.data.endDate,
        // shippingHour: me.data.times[0].val,
        times: me.data.times
      });
    }else{
      if(!me.data.group){
        return;
      }
      me.data.times=[];
      for (let i = min; i < max; i++) {
        me.data.times.push({
          val: i,
          display: i + ':00-' + (i + 1) + ':00'
        });
      }
      let endtime = moment.unix(me.data.group.endDate);
      me.data.startDate = endtime.add(parseInt(me.data.group.days),'d').format('YYYY-MM-DD')
      me.data.endDate = endtime.add(1, 'y').format('YYYY-MM-DD')
      me.setData({
        shippingDay: me.data.startDate,
        startDate: me.data.startDate,
        endDate: me.data.endDate,
        // shippingHour: me.data.times[0].val,
        times: me.data.times
      });
    }
  },
  bindCoupon(e){
    this.setData({
      inputCouponId:e.detail.value
    });
  },
  closeMask(){
    this.setData({
      showPlusAttr:false
    });
  },
  choseGoodPlusAttr(e){
    let me=this;
    let goodsId = e.currentTarget.dataset.item.goodsId;
    let goodsAttrId = e.currentTarget.dataset.item.goodsAttrId;
    let cartId = e.currentTarget.dataset.item.recId;
    http.request({
      url: 'good/getIsPlusAttr/' + goodsId+"/"+cartId,
      loadTip:'查询中',
      success:res=>{
        me.data.goods.forEach((item)=>{
          if(item.recId == cartId){
            item.goodsAttr = "2.0磅";
            me.setData({
              plusGoodAttrId: item.goodsAttrId,
              plusGoodsId:item.goodsId,
              showPlusAttr:false,
              goods:me.data.goods,
              canUseCouponTxt: me.data.tempCouponTxt,
              couponId: me.data.tempCouponId
            });
          }
        })
      }
    });
  },
  queryCoupon() {
    let me = this;
    if(!me.data.inputCouponId){
      return;
    }
    let userId = wx.getStorageSync("userId");
    if (me.data.couponId && me.data.couponId.length>0){
      wx.showToast({
        icon:'none',
        title: '优惠券和优惠码不能同时使用'
      })
      return;
    }
    http.request({
      url: 'coupon/getBaseByCouponId2/' + me.data.inputCouponId + "/" + userId,
      loadTip:'查询中...',
      success: res => {
        if(!res.success){
          wx.showToast({
            title: res.message,
            icon:'none'
          })
          me.setData({
            couponAmount:0,
            couponId: '',
            isCommonCoupon:false
          });
          return;
        }
        if(res.data.type=='加磅'){
          me.setData({
            showPlusAttr:true
          });
        }else{
          me.setData({
            couponAmount: res.data.value,
            canUseCouponTxt: res.data.name,
            couponId: res.data.couponId,
            isCommonCoupon: true
          });
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let me=this;
    this.setData({
      isGroup:options.isGroup=='true' ? true :false,
      goodsAttrId: !options.goodsAttrId ? "" : options.goodsAttrId,
      parentId: !options.parentId ? 0 : options.parentId
    });
    this.getOrderInfo();
    wx.setNavigationBarTitle({
      title: '确认下单'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  getShipFee(p){
    let me=this;
    if(!p){
      return;
    }
    let needShipFee = me.data.goods.find(good=>{
      return good.goodsId == 119 || good.goodsId == 118 || good.goodsId == 73
    })
    if(!needShipFee){
      return;
    }
    let countNumber = 0;
    me.data.goods.forEach(item=>{
      countNumber+=item.goodsNumber
    })
    http.request({
      url: 'region/getShippingFee/'+ p+'/'+countNumber,
      success: res => {
        console.log(res);
        me.setData({
          shippingFee: parseInt(me.data.shippingFee) + parseInt(res.shipFee)
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let me=this;
    this.createTimes();
    this.getUserMoney();
    let chooseAddress =  wx.getStorageSync("chooseAddress");
    let chooseCoupon = wx.getStorageSync("chooseCoupon");
    if (chooseAddress){
      // console.log(chooseAddress.provinceName);
      me.getShipFee(chooseAddress.provinceName);
      setTimeout(()=>{
        me.setData({
          addressInfo: chooseAddress
        });
        wx.removeStorageSync("chooseAddress");
      },150);
    }
    if (chooseCoupon){
      setTimeout(() => {
        if (chooseCoupon.goodsId && chooseCoupon.goodsId > 0){
          let speGood = me.data.goods.find(good=>{
            return good.goodsId == chooseCoupon.goodsId;
          })
          if (!speGood){
            wx.showToast({
              title: '选择的优惠券不适用',
              icon:'none'
            })
            wx.removeStorageSync("chooseCoupon");
            return;
          }
        }
        if (chooseCoupon.type=='加磅'){
          me.setData({
            showPlusAttr: true,
            tempCouponTxt: chooseCoupon.name,
            tempCouponId: chooseCoupon.couponId
          });
        }else{
          me.setData({
            couponAmount: chooseCoupon.value,
            canUseCouponTxt: chooseCoupon.name,
            couponId: chooseCoupon.couponId
          });
        }
        wx.removeStorageSync("chooseCoupon");
      }, 150);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})